package com.yc.weixin.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.yc.utils.YcUtils;
import com.yc.weixin.bean.responseMessage.ResponseArticle;
import com.yc.weixin.bean.responseMessage.ResponseArticleMessage;
import com.yc.weixin.bean.responseMessage.ResponseImage;
import com.yc.weixin.bean.responseMessage.ResponseImageMessage;
import com.yc.weixin.bean.responseMessage.ResponseMusic;
import com.yc.weixin.bean.responseMessage.ResponseMusicMessage;
import com.yc.weixin.bean.responseMessage.ResponseTextMessage;
import com.yc.weixin.entity.Major;
import com.yc.weixin.entity.WeiXinUserRealInfo;
import com.yc.weixin.entity.WeixinUserBaseInfo;
import com.yc.weixin.mapper.CoreServiceMapper;
import com.yc.weixin.service.CoreService;
import com.yc.weixin.util.MessageUtil;
import com.yc.weixin.util.WeiXinCommonUtil;
import com.yc.weixin.util.WeiXinConstants;
import com.yc.weixin.util.WeixinbasicKey;
/**
 * 微信核心实现
 * @author shuang
 *
 */
@Service("coreService")
public class CoreServiceImpl implements CoreService{
	
	private static final Logger logger = Logger.getLogger(CoreServiceImpl.class);
	
	@Resource(name="coreServiceMapper")
	private CoreServiceMapper coreServiceMapper;
	
	public static String openId="";
	
	public String processRequest(HttpServletRequest request) {
		String respXml = null;
		String respContent = WeiXinConstants.HELPER_WELCOME_INFO;
		try {
			//调用解析微信服务器发过来的请求
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			final String fromUserName = requestMap.get("FromUserName");			
			String toUserName = requestMap.get("ToUserName");			
			String createTime=requestMap.get("CreateTime");			
			String msgType = requestMap.get("MsgType");
			//消息id
			String msgId= requestMap.get("MsgId");
	
			openId=fromUserName;//这个是用来绑定微信与学员信息的时候学员微信的openid
			YcUtils.debug(msgType);
			//从消息的类型来分发消息的处理
			if(msgType.equals(MessageUtil.REQUEST_MESSAGE_TYPE_TEXT)){
				String content=requestMap.get("Content");//接收的文本
				// 回复文本消息
				ResponseTextMessage textMessage = new ResponseTextMessage();
				textMessage.setToUserName(fromUserName);
				textMessage.setFromUserName(toUserName);
				textMessage.setCreateTime(new Date().getTime());
				textMessage.setMsgType(MessageUtil.RESPONSE_MESSAGE_TYPE_TEXT);
				
				respContent="您发送的是文本消息";
				//TODO  文本消息的回复
				
				textMessage.setContent(respContent);
				respXml = MessageUtil.messageToXml(textMessage);
				
				//TODO  处理文本消息具体请求，前面的是测试
			}else if(msgType.equals(MessageUtil.REQUEST_MESSAGE_TYPE_LINK)){
				
				String title=requestMap.get("Title");
				
				String description=requestMap.get("Description");
				
				String url=requestMap.get("Url");
				
				//TODO  处理链接消息请求
			}else if(msgType.equals(MessageUtil.RESPONSE_MESSAGE_TYPE_IMAGE)){
				
				String picUrl=requestMap.get("PicUrl");
				//TODO  图片消息处理
			}else if(msgType.equals(MessageUtil.REQUEST_MESSAGE_TYPE_VOICE)){
				//媒体文件标识
				String mediaId=requestMap.get("MediaId");
				//文件格式
				String format=requestMap.get("Format");
				//TODO 处理语音消息请求

				
			}else if(msgType.equals(MessageUtil.REQUEST_MESSAGE_TYPE_VIDEO)){
				//媒体文件标识
				String mediaId=requestMap.get("MediaId");
				//视频消息略缩图的媒体id
				String thumbMediaId=requestMap.get("ThumbMediaId");
				//TODO  处理视频消息请求
			}else if(msgType.equals(MessageUtil.REQUEST_MESSAGE_TYPE_LOCATION)){
				
				String location_x=requestMap.get("Location_x");
				
				String location_y=requestMap.get("Location_y");
				
				String scale=requestMap.get("Scale");
				
				String label=requestMap.get("Label");
				//TODO  地理消息请求处理
			}else if (msgType.equals(MessageUtil.REQUEST_MESSAGE_TYPE_EVENT)) {
				String eventType=requestMap.get("Event");
			   //订阅事件或关注事件
				System.out.println("点击事件的具体类型"+eventType);
				if(MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(eventType)){
					List<ResponseArticle> articles=new ArrayList<ResponseArticle>();					
					articles=coreServiceMapper.selectArticles();
					//调用图文方法回复用户图文信息
					ResponseArticleMessage responseArticleMessage = wrapArticleMessage(articles,fromUserName, toUserName);
					//把图文信息转换成xml格式
					respXml=MessageUtil.messageToXml(responseArticleMessage);
					//新 启动一个线程去处理关注的用户信息添加
					Thread t=new Thread(new Runnable() {
						public void run() {
							try {
								JSONObject userBaseInfo = WeiXinCommonUtil.httpsRequest(WeixinbasicKey.GETUSERBASEINFO.replace("ACCESS_TOKEN", WeixinbasicKey.ACCESSTOKEN).replace("OPENID", openId), "GET", null);
								WeixinUserBaseInfo jb = (WeixinUserBaseInfo)JSONObject.toBean(userBaseInfo,WeixinUserBaseInfo.class);
								if(coreServiceMapper.selectUserInfo(jb.getOpenid())>0){//查询用户是否关注过
									if(coreServiceMapper.updateUserInfo(jb.getOpenid())==0){
										YcUtils.logger.debug(jb+"用户信息存储失败");
										userBaseInfo=null;
									}
								}else{
									int result=coreServiceMapper.insertUserInfo(jb);
									if(result==0){
										YcUtils.logger.debug(jb+"用户信息存储失败");
										userBaseInfo=null;
									}
								}
							} catch (Exception e) {
								YcUtils.logger.error(e.getMessage());
								e.printStackTrace();
							}
						}
					});
					t.start();
				}else if(MessageUtil.EVENT_TYPE_UNSUBSCRIBE.equals(eventType)){
					if(coreServiceMapper.updateSubStatus(fromUserName)==0){
						YcUtils.logger.debug("openid为"+fromUserName+"的用户信息更新失败");
					}
				}else if(MessageUtil.EVENT_TYPE_CLICK.equals(eventType)){
					//TODO  点击事件
				}else if(MessageUtil.EVENT_TYPE_LOCATION.equals(eventType)){
					//TODO 地理事件
				}
				 //TODO    事件类型 具体处理可以见书97页
				}
			
			
		} catch (Exception e) {
			YcUtils.logger.error(e.getMessage());
		}
		return respXml;
	}
	
	
	/**
	 * 将text封装成了文本TxetMessage返回.
	 * @author pj
	 * @param text
	 * @return
	 */
	private ResponseTextMessage wrapTextMessage(String respContent, String fromUserName,String toUserName) {
		ResponseTextMessage textMessage=new ResponseTextMessage();
		textMessage.setFromUserName(toUserName);
		textMessage.setMsgType(MessageUtil.RESPONSE_MESSAGE_TYPE_NEWS);
		textMessage.setToUserName(fromUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setContent(respContent);
		return textMessage;
	}
		
	/**
	 * 将articles封装成了图文ArticleMessage返回.
	 * @author pj
	 * @param articles
	 * @return
	 */
	private ResponseArticleMessage wrapArticleMessage(List<ResponseArticle> articles, String fromUserName,String toUserName) {
		ResponseArticleMessage articleMessage=new ResponseArticleMessage();
		articleMessage.setFromUserName(toUserName);
		articleMessage.setMsgType(MessageUtil.RESPONSE_MESSAGE_TYPE_NEWS);
		articleMessage.setToUserName(fromUserName);
		articleMessage.setCreateTime(new Date().getTime());
		articleMessage.setArticles(articles);
		articleMessage.setArticleCount(articles.size());
		return articleMessage;
	}

	/**
	 * 将music封装成了MusicMessage返回.
	 * @author pj
	 * @param music
	 * @return
	 */
	private ResponseMusicMessage wrapMusicMessage(ResponseMusic music, String fromUserName,String toUserName) {
		ResponseMusicMessage musicMessage = new ResponseMusicMessage();
		musicMessage.setToUserName(fromUserName);
		musicMessage.setFromUserName(toUserName);
		musicMessage.setCreateTime(new Date().getTime());
		musicMessage.setMsgType(MessageUtil.RESPONSE_MESSAGE_TYPE_MUSIC);
		musicMessage.setMusic(music);
		return musicMessage;
	}

	/**
	 * 将图片封装成了ImageMessage返回
	 * @author pj
	 * @param image
	 * @return
	 */
	private ResponseImageMessage returnImageMessage(ResponseImage image, String fromUserName,String toUserName) {
		ResponseImageMessage imageMessage = new ResponseImageMessage();
		imageMessage.setToUserName(toUserName);
		imageMessage.setFromUserName(fromUserName);
		imageMessage.setCreateTime(new Date().getTime());
		imageMessage.setMsgType(MessageUtil.RESPONSE_MESSAGE_TYPE_IMAGE);
		imageMessage.setImage(image);
		return imageMessage;
	}

		/**
		 *获取全部专业
		 */
	@Override
	public List<Major> selectAllMajor() {
		return coreServiceMapper.selectAllMajor();
	}

/**
 * 更新报名用户信息
 */
		@Override
		public int updateUserRealInfo(WeiXinUserRealInfo weiXinUserRealInfo) {
			return coreServiceMapper.updateUserRealInfo(weiXinUserRealInfo);
		}


}
